package org.isouland.cpwx.api.base;

import org.isouland.cpwx.api.core.util.HttpUtil;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.dingpeikeji.quickdeer.core.common.config.Global;

/**
 * 微信授权
 *
 */
public class WxOAuthAPI {
	
	private static Logger logger = LoggerFactory.getLogger(WxOAuthAPI.class);
	
	public static final String access_token_url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	/**
	 * 获取授权code
	 * @param appId
	 * @param code
	 * @return
	 */
	public static String getOpenid(String appId, String secret, String code){
		logger.debug("获取授权code");
		String openid = null;
		String requestUrl = access_token_url.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
		logger.debug("requestUrl={}", requestUrl);
		JSONObject jsonObject = HttpUtil.sendGet(requestUrl);
	    logger.debug("返回的json={}", jsonObject.toString());
	    if (null != jsonObject) {
	    	try{
	    		openid = jsonObject.getString("openid");
	    	} catch(Exception e){
	    		openid = null;
	    	}
	    }
		return openid;
	}
	
	public static void main(String[] args) {
		//String code = "011dAUmg2EfOaO0tJfog2zdUmg2dAUmk";
		String code = "c8d307d9624c4dd89c69fa3c9d83a5ca";
		WxOAuthAPI.getOpenid(Global.getConfig("wx.cp.appid"), Global.getConfig("wx.cp.secret"), code);
	}
	@Test
	public void test(){
		String str = "https://www.xiakeyueche.com/wx/my/myInfoPage?&code=071RVjnl1pxZ7m0FyNkl1DFcnl1RVjnc&state=pu_register";
		System.out.println(str.split("code=")[1].split("&state=")[0]);
	}
}
